﻿#include "GraphicsImageItem.h"
#include <GraphicsUtil.h>
#include <ScaleCommand.h>
#include <GraphicsScene.h>
#include <BoundingMoveStrategy.h>
#include <CenterMoveStrategy.h>
#include <GraphicsMoveOperation.h>
#include <GraphicsTextItem.h>
// #include <AppSettingManager.h>
#include <QPainter>
#include <QCursor>
#include <QGraphicsSceneMouseEvent>
#include <QGraphicsScene>
#include <QTimer>


GraphicsImageItem::GraphicsImageItem(GraphicsBaseItem* parent, GraphicsScene* scene)
	: GraphicsBaseItem(GraphicsItemType::Image_Enum, scene, parent)
{
	// 设置图元的最小尺寸宽度
	m_data.setRealMinSize(QSizeF(32, 32));
	connect(&getItemData(), &GraphicsBaseItemData::sigMaskChanged, this, &GraphicsImageItem::onMaskChanged);
	createTextItem();
}

void GraphicsImageItem::setImage(const QImage& image)
{
	if (!m_scene)
		return;
	m_scene->clearUndoStack();

	m_data.setBaseItemAspectRatio((qreal)image.width() / (qreal)image.height());
	fitImageToSize(1, false);
	m_data.setDefaultSize(QSize(image.width(), image.height()));
	m_data.setOriginImage(image);
}

GraphicsImageItem::~GraphicsImageItem()
{

}

void GraphicsImageItem::initGraphics()
{
	enableMove(true);
	// 设置以图元为中心
	setOriginOnCenter();
	moveToParentCenter();
	m_data.saveContext();
	if (m_scene) {
		m_scene->setSelectItem(this);
	}
	getOperation<GraphicsMoveOperation>(GraphicsOperationType::MoveOperation_Enum)->setMoveStrategy(std::make_shared<CenterMoveStrategy>(getItemData()));
	init();
}

QImage GraphicsImageItem::getImage()
{
	// 调整到768x768
	const qreal imageRation = m_data.getBaseItemAspectRatio();
	QSize ratioSize = GraphicsUtil::getKeepRatioSize(768, 768, imageRation, false).toSize();
	const QImage cutoutImage = m_cutoutImage.scaled(ratioSize, Qt::KeepAspectRatio, Qt::SmoothTransformation);
	return cutoutImage;
}

void GraphicsImageItem::operationDone(GraphicsPinkItemType type, const QPointF& mousePoint)
{
	// 缩放操作
	if (type < GraphicsPinkItem::CornerEnd_Enum) {
		const GraphicsItemInfo itemInfo = m_data.getItemInfo();
		ScaleCommand* scaleCommand = new ScaleCommand(this, m_data.getPressItemInfo(), QMap<GraphicsBaseItem*, GraphicsItemInfo>(),
			itemInfo, QMap<GraphicsBaseItem*, GraphicsItemInfo>());
		m_scene->pushCommand(scaleCommand);
	}
	GraphicsBaseItem::operationDone(type, mousePoint);
}

void GraphicsImageItem::scaleGraphics(GraphicsPinkItemType type, const QPointF& delta)
{
	scaleGraphicsOnCenter(type, delta);
}

void GraphicsImageItem::paint(QPainter* painter, const QStyleOptionGraphicsItem* option, QWidget* widget)
{
	const QRectF rect = m_data.getScaleRect();
	const QSizeF size = rect.size();
	if (size.width() <= 0 || size.height() <= 0)
		return;

	if (m_data.getOriginImage().isNull()) {
		painter->setBrush(QColor("green"));
		painter->drawRect(QRectF(QPointF(-size.width() / 2, -size.height() / 2), size));
		return;
	}

	painter->setRenderHints(QPainter::Antialiasing | QPainter::SmoothPixmapTransform, true);
	painter->save();
	QImage dstImg;
	if (!m_cutoutImage.isNull()) {
		dstImg = m_cutoutImage.scaled(size.toSize(), Qt::KeepAspectRatio, Qt::SmoothTransformation);
	}
	else {
		dstImg = m_data.getOriginImage().scaled(size.toSize(), Qt::KeepAspectRatio, Qt::SmoothTransformation);
	}

	painter->drawImage(QPointF(-size.width() / 2, -size.height() / 2), dstImg);
	// 绘制边框
	QPen pen(m_data.getBorderColor());
	const int penWidth = m_data.getPenWidth();
	pen.setWidth(penWidth);
	painter->setPen(pen);
	painter->drawRect(QRectF(QPointF(-size.width() / 2, -size.height() / 2), size));

	painter->restore();
}

void GraphicsImageItem::mouseReleaseEvent(QGraphicsSceneMouseEvent* event)
{
	GraphicsBaseItem* parentItem = m_data.getParentItem();
	if (!parentItem) {
		GraphicsBaseItem::mouseReleaseEvent(event);
		return;
	}

	GraphicsBaseItemData& parentItemData = parentItem->getItemData();
	const QSizeF realSize = parentItemData.getRealSize();
	QRectF parentRect(0, 0, realSize.width(), realSize.height());

	// box的主体虚线框
	QRectF centerBoxRect(0, 0, m_size.width(), m_size.height());
	centerBoxRect.moveCenter(parentRect.center());

	if (m_textItem->isVisible()) {
		m_textItem->hide();
	}

	// 检查image是否移出box的主体虚线框
	const QRectF realRect = m_data.getRealRect();
	if (centerBoxRect.contains(realRect)) {
		GraphicsBaseItem::mouseReleaseEvent(event);
		return;
	}

	// 检查当天是否弹出显示
	QDateTime nowDateTime = QDateTime::currentDateTime();
	if (nowDateTime.date().day() == m_textShowTime.date().day()) {
		GraphicsBaseItem::mouseReleaseEvent(event);
		return;
	}

	m_textItem->show();
	m_textShowTime = nowDateTime;
	//AppSettingsManager::writeAiBackgroundTipDate(m_textShowTime.toString("yyyy-MM-dd HH:mm:ss"));
	GraphicsBaseItem::mouseReleaseEvent(event);
}

void GraphicsImageItem::init()
{
	moveToParentCenter();
	m_scene->setCenterItem(this);
	// 读取tip显示时间
	//const QString tipShowDateTime = AppSettingsManager::readAiBackgroundTipDate();
	//m_textShowTime = QDateTime::fromString(tipShowDateTime,"yyyy-MM-dd HH:mm:ss");
}

void GraphicsImageItem::createTextItem()
{
	m_textItem = new GraphicsTextItem(this);
	m_textItem->setText(tr("The main image works best with in the dashed frame"));
	m_scene->addItem(m_textItem);
}

void GraphicsImageItem::onMaskChanged()
{
	const QImage originImage = getItemData().getOriginImage();
	// 需要根据mask遮罩图片，调整尺寸大小
	QImage maskImage = getItemData().getMaskImage().scaled(originImage.size());
	// 获取mask的外接矩形
	QRect imageVisableRect = GraphicsUtil::imageBoundingRect(maskImage);
	maskImage = maskImage.copy(imageVisableRect);
	QImage image = originImage.copy(imageVisableRect);
	m_cutoutImage = GraphicsUtil::composeImage(maskImage, image);
	m_data.setBaseItemAspectRatio((qreal)image.width() / (qreal)image.height());
	fitImageToSize(1, false);
	// 更新图元的尺寸
	update();
}

void GraphicsImageItem::fitImageToSize(qreal fitFactor, bool isScale)
{
	// 调整Image的尺寸,Image的最大显示范围
	const qreal imageRation = m_data.getBaseItemAspectRatio();
	const qreal maxImageWidth = m_size.width() * fitFactor;
	const qreal maxImageHeight = m_size.height() * fitFactor;
	//在maxImageWidth和maxImageHeight尺寸下的Image最大尺寸
	qreal imageWidth = maxImageWidth;
	qreal imageHeight = maxImageHeight;
	const qreal fitImageWidth = (imageRation == 0) ? 32 : (maxImageHeight * imageRation);
	const qreal fitImageHeight = (imageRation == 0) ? 32 : (maxImageWidth / imageRation);
	if (fitImageWidth >= maxImageWidth) {
		// 当以宽为基准
		imageWidth = maxImageWidth;
		imageHeight = imageWidth / imageRation;
	}
	else {
		// 当以高为基准
		imageHeight = maxImageHeight;
		imageWidth = imageHeight * imageRation;
	}
	if (isScale) {
		getItemData().setScaleSize(QSizeF(imageWidth, imageHeight));
	}
	else {
		getItemData().setRealSize(QSizeF(imageWidth, imageHeight));
	}
	moveToParentCenter();
}
